package org.footballmanager.pandafootball.system.controller.hy;

import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.system.controller.BaseController;
import org.footballmanager.pandafootball.system.domain.*;
import org.footballmanager.pandafootball.system.domain.enums.JNFL;
import org.footballmanager.pandafootball.system.form.impl.FootClubSearchForm;
import org.footballmanager.pandafootball.system.form.impl.FootPersonSearchForm;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/hy/footClub")
public class HyClubController extends BaseController {
    /* 实体名称 */
    private static final String ENTITYNAME = "footClub";
    private static final String LISTPAGE = String.format(Constants.LISTPAGE, Constants.HY, ENTITYNAME);
    private static final String VIEWPAGE = String.format(Constants.VIEWPAGE, Constants.HY, ENTITYNAME);
    private static final String QYLIST = "qyList";

    @Autowired
    private FootClubService footClubService;
    @Autowired
    private FootPersonService footPersonService;
    @Autowired
    private FootUserPersonService footUserPersonService;
    @Autowired
    private FootSjService footSjService;
    @Autowired
    private FootUserService footUserService;
    @Autowired
    private FootQdService footQdService;
    @Autowired
    private FootTableTitleService footTableTitleService;


    /**
     * 初始化
     *
     * @param map 参数
     */
    @ModelAttribute
    public void init(Model map, @ModelAttribute FootClubSearchForm footClubSearchForm) {
        map.addAttribute("userList", footUserService.findGameIdIsNotNull());
        map.addAttribute("sjList", footSjService.getall());
        map.addAttribute("qdList", footQdService.getall());
        map.addAttribute("head", footTableTitleService.findByTableName(Constants.PERSONTABLE));
        FootClubSearchForm newFootClubSearchForm = new FootClubSearchForm();
        if (footClubSearchForm != null) {
            newFootClubSearchForm = footClubSearchForm;
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newFootClubSearchForm);
    }

    @RequestMapping(value = "/search")
    public String search(Model map, @ModelAttribute FootClubSearchForm footClubSearchForm) {
        footClubSearchForm.setSj(footSjService.getSj());
        footClubService.search(ENTITYNAME, map, footClubSearchForm);
        return LISTPAGE;
    }

    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String openViewPage(Model map, @RequestParam Long id, HttpServletRequest request,
                               @ModelAttribute FootClubSearchForm footClubSearchForm) {
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), footClubSearchForm);
        FootUser user = (FootUser) request.getSession().getAttribute(Constants.USER);
        map.addAttribute(ENTITYNAME, footClubService.get(id));
        List<FootPerson> list = footUserPersonService.findFootPersonByUserId(user.getId(), request);
        if (list != null && !list.isEmpty()) {
            double sum = 0D;
            for (FootPerson person : list) {
                sum += Double.valueOf(person.getQysj());
            }
            map.addAttribute("sum", sum);
            map.addAttribute(QYLIST, list);
        }
        map.addAttribute("power", footUserPersonService.getPower(user.getId(), request));
        return VIEWPAGE;
    }

    @RequestMapping(value = "see", method = RequestMethod.GET)
    public String see(Model map, @RequestParam Long id, @RequestParam Long clubId) {
        map.addAttribute("footPerson", footPersonService.get(id));
        map.addAttribute("id", clubId);
        map.addAttribute("basicSkills", footTableTitleService.findByTableNameAndJnfl(Constants.PERSONTABLE, JNFL.BASIC));
        map.addAttribute("linkageSkills", footTableTitleService.findByTableNameAndJnfl(Constants.PERSONTABLE, JNFL.LINKAGE));
        return "hy/footClub/QyView";
    }

    @RequestMapping(value = "/viewList", method = RequestMethod.GET)
    public String openViewListPage(Model map, HttpServletRequest request) {
        FootUser user = (FootUser) request.getSession().getAttribute(Constants.USER);
        FootClub club = footClubService.findByUserid(user.getId());
        if (club != null) {
            map.addAttribute(ENTITYNAME, club);
        }
        List<FootPerson> list = footUserPersonService.findFootPersonByUserId(user.getId(), request);
        if (null != list && !list.isEmpty()) {
            double sum = 0D;
            for (FootPerson json : list) {
                sum += Double.valueOf(json.getQysj());
            }
            map.addAttribute("sum", sum);
            map.addAttribute(QYLIST, list);
        }
        map.addAttribute("power", footUserPersonService.getPower(user.getId(), request));
        return VIEWPAGE;
    }

    @RequestMapping(value = "/changePerson", method = RequestMethod.POST)
    @ResponseBody
    public FootPerson changePerson(Model map, HttpServletRequest request, @ModelAttribute FootPersonSearchForm footPersonSearchForm) {
        FootUser user = (FootUser) request.getSession().getAttribute(Constants.USER);
        String[] result = footPersonSearchForm.getSelectIds().split(Constants.COMMA);
        if (result.length != 5) {
            map.addAttribute(QYLIST, footUserPersonService.findFootPersonByUserId(user.getId(), request));
            return null;
        } else {
            Integer total = 0;
            for (String id : result) {
                String[] ci = id.split(":");
                FootPerson fp = footPersonService.get(Long.parseLong(ci[0]));
                total += fp.getPf();
                footUserPersonService.deletePersonFromMyTeam(user.getId(), Long.parseLong(ci[0]), Integer.valueOf(ci[1]), request);
            }
            int avg = total / 5;
            return processAvg(avg, user, request);
        }
    }

    private FootPerson processAvg(int avg, FootUser user, HttpServletRequest request) {
        if (avg >= 90) {
            return footPersonService.findPersonByScore("90", null, user.getId(), request);
        } else if (avg >= 84) {
            return footPersonService.findPersonByScore("84", "89", user.getId(), request);
        } else if (avg >= 80) {
            return footPersonService.findPersonByScore("80", "83", user.getId(), request);
        } else if (avg >= 75) {
            return footPersonService.findPersonByScore("75", "79", user.getId(), request);
        } else {
            return footPersonService.findPersonByScore("0", "74", user.getId(), request);
        }
    }

    @RequestMapping(value = "/checkPerson", method = RequestMethod.POST)
    @ResponseBody
    public JsonReturn checkPerson(@RequestParam Long fupid, HttpServletRequest request) {
        FootUser user = (FootUser) request.getSession().getAttribute(Constants.USER);
        //查找主力球员，看看是否超过18个
        int mainPerson = footUserPersonService.checkMainPerson(user);
        FootUserPerson fup = footUserPersonService.get(fupid);
        //处理主力球员
        if (null != fup) {
            if (fup.getMain()) {
                fup.setMain(false);
                footUserPersonService.updateNotNull(fup, request);
                return new JsonReturn(Constants.OK);
            } else if (!fup.getMain() && mainPerson < 18 && !footUserPersonService.findPersonMain(user.getId(), fup)) {
                fup.setMain(true);
                footUserPersonService.updateNotNull(fup, request);
                return new JsonReturn(Constants.OK);
            }
        }
        return new JsonReturn(Constants.ERROR);
    }

    @RequestMapping(value = "/updatePerson", method = RequestMethod.POST)
    @ResponseBody
    public JsonReturn updatePerson(Model map, HttpServletRequest request, @ModelAttribute FootPersonSearchForm footPersonSearchForm) {
        FootUser user = (FootUser) request.getSession().getAttribute(Constants.USER);
        String[] result = footPersonSearchForm.getSelectIds().split(Constants.COMMA);
        String[] qy1 = result[0].split(":");
        String[] qy2 = result[1].split(":");
        if (result.length != 2 || !qy1[0].equals(qy2[0])) {
            map.addAttribute(QYLIST, footUserPersonService.findFootPersonByUserId(user.getId(), request));
            return new JsonReturn("选择球员不符合升级条件，请重新选择");
        } else {
            return footUserPersonService.compose(Long.parseLong(qy1[2]), Long.parseLong(qy2[2]), request);
        }
    }
}
